import decimal
from flask_restful import Resource
from flask import request, jsonify
from fullstack import app, api, db
from fullstack.utils import to_json, paginate, getCurrentTime,getCurrentDate
from fullstack.Models.food.Food import Food
from fullstack.Models.food.FoodStockChangeLog import FoodStockChangeLog
from fullstack.Models.food.FoodSaleChangeLog import FoodSaleChangeLog
from fullstack.Models.member.OauthMemberBind import OauthMemberBind
from fullstack.Models.pay.PayOrderItem import PayOrderItem


SECTION_URL = '/vue/api/foods'


class FoodList(Resource):
    def get(self):
        # 查询参数
        res = request.values
        query = res['query']
        status = query
        if not is_number(query):
            status = -1
        pagenum = int(res['pagenum'])
        pagesize = int(res['pagesize'])
        ret = paginate(pagenum, pagesize)
        flag = True
        # query字符串为空
        if not query.strip():
            sql = '''
            SELECT* 
            FROM food
            LIMIT {0},{1}
            '''.format(ret['offset'], ret['limit'])
            counts = Food.query.count()

        else:
            sql = '''
            SELECT* 
            FROM food
            WHERE category='{0}' OR status={1} OR name LIKE '%%{0}%%'  
            '''.format(query, status)
            flag = False
            print(status)
        #  OR status='{0}'

        result = db.engine.execute(sql)
        responseData = dict()
        jsonData = list()
        for row in result:
            jsonData.append(to_json(Food, row))

        if not flag:
            counts = len(jsonData)

        responseData['total'] = counts
        # 当前页
        responseData['pagenum'] = 1
        responseData['foods'] = jsonData

        return responseData

    def post(self):
        response = {'meta': {'status': 200, 'msg': '修改成功'}}
        rest = request.json.get('data')
        status = int(rest['status']) if 'status' in rest else 0
        cover = int(rest['cover']) if 'cover' in rest else 0
        id = int(rest['id'])
        food = Food.query.get(id)
        food.category = rest['category']
        food.name = rest['name']
        food.priced = decimal.Decimal(rest['priced'])
        food.price = decimal.Decimal(rest['price'])
        food.stock = int(rest['stock'])
        food.status = status
        food.cover = cover
        food.imageName = rest['imageName']
        food.imageURL = rest['imageURL']
        food.description = rest['description']
        food.updated_time = getCurrentTime()
        db.session.commit()
        return jsonify(response)

    def delete(self):
        print(request.values)
        res = request.values
        id = int(res['id'])
        sql = '''
        DELETE FROM food
        WHERE id={0}
        '''.format(id)
        result = db.engine.execute(sql)
        return jsonify(status=200)

    def patch(self):
        rest = request.json.get('data')
        id = int(rest['id'])
        status = int(rest['status']) if 'status' in rest else None
        cover = int(rest['cover']) if 'cover' in rest else None
        if not status == None:
            sql = '''
            UPDATE food
            SET status={0}
            WHERE id={1}
            '''.format(status, id)
            db.engine.execute(sql)

        if not cover == None:
            sql = '''
            UPDATE food
            SET cover={0}
            WHERE id={1}
            '''.format(cover, id)
            db.engine.execute(sql)

        return jsonify(status=200)


api.add_resource(FoodList, SECTION_URL+'/list')


def is_number(s):
    try:  # 如果能运行float(s)语句，返回True（字符串s是浮点数）
        float(s)
        return True
    except ValueError:  # ValueError为Python的一种标准异常，表示"传入无效的参数"
        pass  # 如果引发了ValueError这种异常，不做任何事情（pass：不做任何事情，一般用做占位语句）
    try:
        import unicodedata  # 处理ASCii码的包
        for i in s:
            unicodedata.numeric(i)  # 把一个表示数字的字符串转换为浮点数返回的函数
            # return True
        return True
    except (TypeError, ValueError):
        pass
    return False


# 库存变更日志
class FoodStockLog(Resource):
    def get(self):
        # 从请求中得到food_id
        res = request.values
        resp = {'code': 200, 'data': []}
        if not res['id']:
            return jsonify(resp)

        id = int(res['id'])
        pagenum = int(res['pagenum']) if (
            'pagenum' in res and res['pagenum']) else 1
        pagesize = int(res['pagesize']) if (
            'pagesize' in res and res['pagesize']) else 5
        ret = paginate(pagenum, pagesize)
        result = FoodStockChangeLog.query.filter_by(food_id=id).order_by(FoodStockChangeLog.created_time.desc()).offset(ret['offset']).limit(
            ret['limit'])
        if result:
            total = result.count()
            stock_list = []
            for item in result:
                temp_data = {
                    "food_id": item.food_id,
                    "unit": item.unit,
                    "total_stock": item.total_stock,
                    "note": item.note,
                    "created_time": item.created_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                stock_list.append(temp_data)

            resp['data'] = stock_list
        else:
            total = 0

        resp['total'] = total

        return jsonify(resp)


api.add_resource(FoodStockLog, SECTION_URL+'/log/stock')

# 商品售卖日志
class FoodSaleLog(Resource):
    def get(self):
        res = request.values
        resp = {'code': 200, 'data': []}
        if not res['id']:
            return jsonify(resp)
        id=int(res['id'])
        pagenum = int(res['pagenum']) if (
            'pagenum' in res and res['pagenum']) else 1
        pagesize = int(res['pagesize']) if (
            'pagesize' in res and res['pagesize']) else 5
        ret = paginate(pagenum, pagesize)
        result = FoodSaleChangeLog.query.filter_by(food_id=id,status=1).order_by(FoodSaleChangeLog.created_time.desc()).offset(ret['offset']).limit(
            ret['limit'])
        if result:
            total = result.count()
            sale_list = []
            for item in result:
                temp_data = {
                    "food_id": item.food_id,
                    "order_id": item.order_id,
                    "member_id": item.member_id,
                    "price": str(item.price),
                    "quantity": item.quantity,
                    "created_time": item.created_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                sale_list.append(temp_data)

            resp['data'] = sale_list
        else:
            total = 0

        resp['total'] = total

        return jsonify(resp)


api.add_resource(FoodSaleLog, SECTION_URL+'/log/sale')

class FoodMonthCount(Resource):
    def get(self):
        # 月销量更新
        date = getCurrentDate()
        item_model = PayOrderItem.query.filter(
            PayOrderItem.created_time.like("%" + date + "%")).filter_by(status=1)
        if item_model:
            for item in item_model:
                food_model = Food.query.filter_by(
                    id=item.food_id).first()
                if food_model:
                    food_model.month_count = food_model.month_count+item.quantity
                    db.session.add(food_model)
                    db.session.commit()  
        return jsonify(status=200)

api.add_resource(FoodMonthCount, SECTION_URL+'/log/month')
